// ================================================================
// 4. PERIODIC EVALUATIONS PAGE
// ================================================================

import * as React from "react"
import { Metadata } from "next"
import { type SearchParams } from "@/types/table"
import { getValidFilters } from "@/lib/data-table"
import { Shell } from "@/components/shell"
import { DataTableSkeleton } from "@/components/data-table/data-table-skeleton"
import { HelpCircle } from "lucide-react"
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { PeriodicEvaluationsTable } from "@/lib/evaluation/table/evaluation-table"
import { getPeriodicEvaluations } from "@/lib/evaluation/service"
import { searchParamsEvaluationsCache } from "@/lib/evaluation/validation"

export const metadata: Metadata = {
  title: "협력업체 정기평가",
  description: "협력업체 정기평가 진행 현황을 관리합니다.",
}

interface PeriodicEvaluationsPageProps {
  searchParams: Promise<SearchParams>
}

// 프로세스 안내 팝오버 컴포넌트
function ProcessGuidePopover() {
  return (
    <Popover>
      <PopoverTrigger asChild>
        <Button variant="ghost" size="icon" className="h-6 w-6">
          <HelpCircle className="h-4 w-4 text-muted-foreground" />
        </Button>
      </PopoverTrigger>
      <PopoverContent className="w-96" align="start">
        <div className="space-y-3">
          <div className="space-y-1">
            <h4 className="font-medium">정기평가 프로세스</h4>
            <p className="text-sm text-muted-foreground">
              확정된 평가 대상 업체들에 대한 정기평가 절차입니다.
            </p>
          </div>
          <div className="space-y-3 text-sm">
            <div className="flex gap-3">
              <div className="flex h-6 w-6 items-center justify-center rounded-full bg-blue-100 text-xs font-medium text-blue-600">
                1
              </div>
              <div>
                <p className="font-medium">평가 대상 확정</p>
                <p className="text-muted-foreground">평가 대상으로 확정된 업체들의 정기평가가 자동 생성됩니다.</p>
              </div>
            </div>
            <div className="flex gap-3">
              <div className="flex h-6 w-6 items-center justify-center rounded-full bg-blue-100 text-xs font-medium text-blue-600">
                2
              </div>
              <div>
                <p className="font-medium">업체 자료 제출</p>
                <p className="text-muted-foreground">각 업체는 평가에 필요한 자료를 제출 마감일까지 제출해야 합니다.</p>
              </div>
            </div>
            <div className="flex gap-3">
              <div className="flex h-6 w-6 items-center justify-center rounded-full bg-blue-100 text-xs font-medium text-blue-600">
                3
              </div>
              <div>
                <p className="font-medium">평가자 검토</p>
                <p className="text-muted-foreground">지정된 평가자들이 평가표를 기반으로 점수를 매기고 검토합니다.</p>
              </div>
            </div>
            <div className="flex gap-3">
              <div className="flex h-6 w-6 items-center justify-center rounded-full bg-blue-100 text-xs font-medium text-blue-600">
                4
              </div>
              <div>
                <p className="font-medium">최종 확정</p>
                <p className="text-muted-foreground">모든 평가가 완료되면 최종 점수와 등급이 확정됩니다.</p>
              </div>
            </div>
          </div>
        </div>
      </PopoverContent>
    </Popover>
  )
}

// TODO: 이 함수들은 실제 서비스 파일에서 구현해야 함
function getDefaultEvaluationYear() {
  return new Date().getFullYear()
}



export default async function PeriodicEvaluationsPage(props: PeriodicEvaluationsPageProps) {
  const searchParams = await props.searchParams
  const search = searchParamsEvaluationsCache.parse(searchParams)
  const validFilters = getValidFilters(search.filters || [])

  // 기본 필터 처리
  let basicFilters = []
  if (search.basicFilters && search.basicFilters.length > 0) {
    basicFilters = search.basicFilters
  }

  // 모든 필터를 합쳐서 처리
  const allFilters = [...validFilters, ...basicFilters]
     
  // 조인 연산자
  const joinOperator = search.basicJoinOperator || search.joinOperator || 'and';

  // 현재 평가년도
  const currentEvaluationYear = search.evaluationYear || getDefaultEvaluationYear()

  // Promise.all로 감싸서 전달
  const promises = Promise.all([
    getPeriodicEvaluations({
      ...search,
      filters: allFilters,
      joinOperator,
    })
  ])

  return (
    <Shell className="gap-4">
      {/* 헤더 */}
      <div className="flex items-center justify-between space-y-2">
        <div className="flex items-center justify-between space-y-2">
          <div className="flex items-center gap-2">
            <h2 className="text-2xl font-bold tracking-tight">
              협력업체 정기평가
            </h2>
            <Badge variant="outline" className="text-sm">
              {currentEvaluationYear}년도
            </Badge>
          </div>
        </div>
      </div>
             
      {/* 메인 테이블 */}
      <React.Suspense 
        key={JSON.stringify(searchParams)}
        fallback={
          <DataTableSkeleton
            columnCount={15}
            searchableColumnCount={2}
            filterableColumnCount={8}
            cellWidths={[
              "3rem",   // checkbox
              "5rem",   // 평가년도
              "5rem",   // 평가기간
              "4rem",   // 구분
              "8rem",   // 벤더코드
              "12rem",  // 벤더명
              "4rem",   // 내외자
              "6rem",   // 자재구분
              "5rem",   // 문서제출
              "4rem",   // 제출일
              "4rem",   // 마감일
              "4rem",   // 총점
              "4rem",   // 등급
              "5rem",   // 진행상태
              "8rem"    // actions
            ]}
            shrinkZero
          />
        }
      >
        <PeriodicEvaluationsTable
          promises={promises} 
          evaluationYear={currentEvaluationYear}
        />
      </React.Suspense>
    </Shell>
  )
}